#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int max(int a, int b) {
    return (a > b) ? a : b;
}

void longestNonDecreasingSubsequence(int arr[], int n) {
    if (n == 0) {
//        printf("最长非递减子序列: \n长度: 0\n");
        return;
    }

    int *dp = (int*)malloc(n * sizeof(int));
    int *prev = (int*)malloc(n * sizeof(int));

    for (int i = 0; i < n; i++) {
        dp[i] = 1;
        prev[i] = -1;
    }

    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (arr[j] <= arr[i] && dp[j] + 1 > dp[i]) {
                dp[i] = dp[j] + 1;
                prev[i] = j;
            }
        }
    }

    int maxLen = 0;
    int endIdx = 0;
    for (int i = 0; i < n; i++) {
        if (dp[i] > maxLen) {
            maxLen = dp[i];
            endIdx = i;
        }
    }

    int *lis = (int*)malloc(maxLen * sizeof(int));
    int idx = maxLen - 1;
    int current = endIdx;

    while (current != -1) {
        lis[idx] = arr[current];
        current = prev[current];
        idx--;
    }

//    printf("最长非递减子序列: ");
    for (int i = 0; i < maxLen; i++) {
        printf("%d ", lis[i]);
    }
//    printf("\n长度: %d\n", maxLen);

    free(dp);
    free(prev);
    free(lis);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "使用方法: %s \"[元素1, 元素2, ..., 元素n]\"\n", argv[0]);
        return 1;
    }

    char *input = argv[1];
    int len = strlen(input);

    if (len < 2 || input[0] != '[' || input[len-1] != ']') {
        fprintf(stderr, "输入格式有误，应该为 [元素1, 元素2, ..., 元素n]\n");
        return 1;
    }

    // 复制输入字符串并移除方括号
    char *copy = (char*)malloc(len * sizeof(char));
    strncpy(copy, input + 1, len - 2);
    copy[len - 2] = '\0';

    // 计算元素数量
    int count = 0;
    char *token = strtok(copy, ",");
    while (token != NULL) {
        count++;
        token = strtok(NULL, ",");
    }

    // 重新分配内存并解析元素
    int *arr = (int*)malloc(count * sizeof(int));
    strncpy(copy, input + 1, len - 2);
    copy[len - 2] = '\0';

    int i = 0;
    token = strtok(copy, ",");
    while (token != NULL) {
        arr[i++] = atoi(token);
        token = strtok(NULL, ",");
    }

    longestNonDecreasingSubsequence(arr, count);

    free(copy);
    free(arr);

    return 0;
}